#include "recbox.h"
#include "ui_recbox.h"
#include "recboxitem.h"
#include"QJsonObject"
#include<math.h>
recbox::recbox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::recbox),
    row(1),
    col(4)
{
    ui->setupUi(this);
}

void recbox::InitrecboxUI(QJsonArray array, int row)
{
    currentindex=0;
    as=array;
    if(row==2)
    {
        this->row=row;
        this->col=8;
    }
    else
    {
        ui->recdown->hide();
    }
    count=ceil(as.size()/col);
    createrecboxitem();
}

void recbox::createrecboxitem()
{
    QList<recboxitem*> ret=ui->recup->findChildren<recboxitem*>();
    for(auto e:ret)
    {
        ui->horizontalLayout_4->removeWidget(e);
        delete e;
    }
    QList<recboxitem*> rets=ui->recdown->findChildren<recboxitem*>();
    for(auto e:rets)
    {
        ui->horizontalLayout_5->removeWidget(e);
        delete e;
    }
    int jk=0;
    for(int i=currentindex*col;i<col+currentindex*col;i++)
    {
        recboxitem* f=new recboxitem();
        QJsonObject obj=as[i].toObject();
        f->setText(obj.value("text:").toString());
        f->setImage(obj.value("path:").toString());
        if(jk>=col/2&&row==2)
        {
            ui->horizontalLayout_5->addWidget(f);
        }
        else
        {
          ui->horizontalLayout_4->addWidget(f);
        }
        jk++;
    }
}

recbox::~recbox()
{
    delete ui;
}

void recbox::on_rightbutton_clicked()
{
    currentindex++;
    if(currentindex>=count)
    {
        currentindex=0;
    }
    createrecboxitem();
}

void recbox::on_leftbutton_clicked()
{
    currentindex--;
    if(currentindex<0)
    {
        currentindex=0;
    }
    createrecboxitem();
}
